import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes ,resetRouter} from '@/router'
const state = {
  token: getToken(),
  userInfo: {} ,// 这里有一个空对象，为了放置后面取数据报错
  routes: constantRoutes 
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken() {
    // 删除vuex的token
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]  //静态路由 加动态路由

  }

}
const actions = {
  async login(context, data) {
    console.log(data)
    const token = await login(data)
    context.commit('setToken', token)
  },
  // 获取用户的基本资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result //返回数据
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken')// 删除token
    context.commit('setUserInfo', {})// 设置用户信息为空对象
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
